package com.matthicks.macrobot.pdfocr;

import java.awt.Point;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.matthicks.macrobot.Key;
import com.matthicks.macrobot.RemoteController;

public class OCRPDF {
	public static final String PROCESS_NAME = "Transformer.exe";
	
	private RemoteController rc;
	
	public OCRPDF() throws UnknownHostException, IOException {
		rc = new RemoteController("192.168.42.128", 2600);
	}
	
	public void launch() throws InterruptedException {
		if (!rc.isProcessRunning(PROCESS_NAME)) {
			System.out.println("Transformer is not running. Starting...");
			
			// Launch shortcut
			rc.keyPress(Key.CONTROL);
			rc.keyPress(Key.ALT);
			rc.keyType(Key.P);
			rc.keyRelease(Key.ALT);
			rc.keyRelease(Key.CONTROL);
			
			// Wait for process
			if (!rc.waitForProcess(PROCESS_NAME, 30000, true)) {
				throw new RuntimeException("Transformer process did not start.");
			}
			
			// Move mouse just in case
			rc.mouseMove(100, 100, 1.0f);
			
			// Wait for screen to appear
			if (rc.screenContains(0, 0, "abbyy_open_pdf.png", 2.0f, 10) == null) {
				throw new RuntimeException("Transformer was not found on screen.");
			}
			
			System.out.println("Transformer launched successfully.");
		} else {
			System.out.println("Transformer is already running");
		}
	}
	
	public void processDirectory(File directory) throws InterruptedException {
		List<File> store = new ArrayList<File>();
		findPDFs(directory, store);
		
		System.out.println("PDFs to Process: " + store.size());
		process(store);
	}
	
	private void findPDFs(File directory, List<File> store) {
		for (File f : directory.listFiles()) {
			if (f.isDirectory()) {
				findPDFs(f, store);
			} else if (f.getName().toLowerCase().endsWith(".pdf")) {
				if (f.getParentFile().getName().equals("pdf")) {
					store.add(f);
				}
			}
		}
	}
	
	private void process(List<File> store) throws InterruptedException {
		for (int i = 0; i < store.size(); i++) {
			processFile(store.get(i), i, store.size());
		}
	}
	
	public boolean processFile(File file, int index, int total) {
		File txt = new File(file.getParentFile(), file.getName().substring(0, file.getName().indexOf('.')) + ".txt");
		if (!txt.exists()) {
			System.out.println("Processing: " + file.getAbsolutePath() + " (" + (index + 1) + " of " + total + ")");
			
			Point p = rc.screenContains(0, 0, "abbyy_open_pdf.png", 5.0f, 5);
			if (p == null) {
				throw new RuntimeException("Unable to find Open PDF button");
			}
			rc.mouseMove(p.x, p.y, 1.0f);
			rc.mouseClick();
			
			// Make sure dialog came up
			if (rc.screenContains(0, 0, "abbyy_open_dialog.png", 2.0f, 10) == null) {
				throw new RuntimeException("Unable to find open dialog.");
			}
			
			// Rename file if invalid
			String name = file.getName();
			name = name.replaceAll(",", "_");
			if (!name.equals(file.getName())) {
				System.out.println("\tRenaming from " + file.getName() + " to " + name);
				File n = new File(file.getParentFile(), name);
				file.renameTo(n);
				file = n;
			}
			
			// Type PDF filename in
			String filename = file.getAbsolutePath();
			rc.stringType(filename.replaceAll("/", "\\\\"));
			rc.keyType(Key.ENTER);
			
			// Wait for PDF to be scanned
			if (rc.screenContains(0, 0, "abbyy_pdf_scanned.png", 5.0f, 10) == null) {
				throw new RuntimeException("PDF did not load successfully");
			}
			
			// Click "Convert"
			p = rc.screenContains(0, 0, "abbyy_convert_pdf.png", 5.0f, 10);
			if (p == null) {
				throw new RuntimeException("Unable to find convert button");
			}
			rc.mouseMove(p.x, p.y, 1.0f);
			rc.mouseClick();
			
			// Wait for Notepad
			p = rc.screenContains(0, 0, "abbyy_notepad.png", 5.0f, 30);
			if (p == null) {
				throw new RuntimeException("Unable to find Notepad.");
			}
			rc.keyPress(Key.ALT);
			rc.keyType(Key.F4);
			rc.keyRelease(Key.ALT);
			
			// Close warnings
			p = rc.screenContains(0, 0, "abbyy_warnings_close.png", 2.0f, 3);
			if (p != null) {
				rc.mouseMove(p.x, p.y, 1.0f);
				rc.mouseClick();
			}
		} else {
			System.out.println("\t" + txt.getAbsolutePath() + " already exists. Skipping.");
		}
		
		return true;
	}
	
	public void kill() {
		rc.killProcess("Transformer.exe");
	}
	
	public void disconnect() throws IOException {
		rc.disconnect();
	}
	
	public static void main(String[] args) throws Exception {
		File directory = new File("//bluemeanie.imirus.local/ftp/ocrproboat/464");
		
		OCRPDF ocr = new OCRPDF();
		try {
			ocr.launch();
			ocr.processDirectory(directory);
//			ocr.kill();
		} finally {
			ocr.disconnect();
		}
	}
}
